import api from '../../../common/api.js'
import mapConfig from '../../../utils/mapConfig';
import locationBehavior from '../../../behaviors/location.js';
import {
  insertHouseLog
} from '../../../common/log.js';
import * as transferData from '../../../models/transferData'
const cityMap = require("./../../../utils/city");

const qqmapsdk = mapConfig.qqmapsdk;
const app = getApp()

Page({
  behaviors: [locationBehavior],

  data: {
    _firstCity: {},
    latitude: "",
    longitude: "",
    scale: 16,
    markers: [{
      iconPath: "/images/marker.png",
      id: 0,
      latitude: "",
      longitude: "",
      width: 20,
      height: 20,
    }],
    rows: [],
    loading: true,
    city: {},
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // 系统定位未开启 退出页面
    this.initData(options)
    this.checkSystemLocationAuth()
    app.mobileLogin()
      .then(() => {
        const city = app.globalData._wx_city || wx.getStorageSync("_wx_city");
        let cityCode = "";
        cityMap.cityObjs.forEach((item) => {
          if (item.city === city) {
            cityCode = item.code || "";
          }
        });
        if (city) {
          this.resetCityByCityName({
            city,
            cityCode
          })
        } else {
          this.uploadLog()
          this.checkUserLocationAuth()
            .then(() => {
              this.updateMapByLocation()
            })
            .catch(() => {
              this.reqUserLocationAuth()
                .then(() => {
                  this.updateMapByLocation()
                })
                .catch(() => {
                  this.updateMapByDefaultLocation()
                })
            })
        }
      })
      .catch(() => {
        app.globalData.afterMobileAuthorCallBack = () => {
          wx.redirectTo({
            url: '/pages/cooperation/choose/choose',
          })
        }
      })
  },

  /**
   * 生命周期函数--监听页面显示
   */

  onShow: function () {
    this.myData.entryPageCount++
    this.refreshCity()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  initData() {
    this.myData = {
      entryPageCount: 0,
      mapCtx: wx.createMapContext('map'),
    }
  },

  uploadLog() {
    let currentCity = wx.getStorageSync('currentCity') || {}
    insertHouseLog({
      logType: "1",
      cityName: currentCity.city || "上海市",
      inputHouseType: app.getCurrentStatusName()
    })
  },

  // 检查手机系统定位开关状态
  checkSystemLocationAuth() {
    wx.getSystemInfo({
      success(res) {
        if (!res.locationEnabled && res.locationEnabled !== undefined) {
          wx.showModal({
            content: '请打开GPS后再使用！',
            showCancel: false,
            complete(res) {
              wx.navigateBack({
                delta: 1,
              })
            }
          })
        }
      }
    })
  },

  // 检查用户定位授权
  checkUserLocationAuth() {
    return new Promise((resolve, reject) => {
      wx.getSetting({
        success: (res) => {
          if (res.authSetting['scope.userLocation']) {
            resolve()
          } else {
            reject()
          }
        }
      })
    })
  },

  // 请求授权用户定位权限
  reqUserLocationAuth() {
    return new Promise((resolve, reject) => {
      wx.authorize({
        scope: 'scope.userLocation',
        success: () => {
          resolve()
        },
        fail: () => {
          reject()
        },
      })
    })
  },

  // 通过默认定位更新地图
  updateMapByDefaultLocation() {
    const latitude = "31.239580";
    const longitude = "121.499763";
    this.setData({
      latitude,
      longitude,
      markers: [{
        iconPath: "/images/marker.png",
        id: 0,
        latitude,
        longitude,
        width: 20,
        height: 20,
      }],
    })
    this.updateMapByCoordinate({
      latitude: latitude,
      longitude: longitude,
    })
  },

  // 通过实时定位更新地图
  updateMapByLocation() {
    return new Promise((resolve, reject) => {
      wx.getLocation({
        type: 'gcj02',
        isHighAccuracy: true,
        success: (site) => {
          this.setData({
            latitude: site.latitude,
            longitude: site.longitude,
            markers: [{
              iconPath: "/images/marker.png",
              id: 0,
              latitude: site.latitude,
              longitude: site.longitude,
              width: 20,
              height: 20,
            }],
          })
          this.updateMapByCoordinate({
            latitude: site.latitude,
            longitude: site.longitude,
          })
        }
      })
    })
  },

  // 通过经纬度更新地图
  updateMapByCoordinate({
    latitude,
    longitude
  }) {
    this.getCurrentCityByLatlng(latitude, longitude)
      .then((city) => {
        let currentCity = wx.getStorageSync('currentCity') || {}
        if (!(currentCity && currentCity.city && currentCity.cityCode)) {
          wx.setStorageSync('currentCity', city)
        }
        if (this.myData.entryPageCount === 1) {
          this.data._firstCity = {
            cityName: city ? city.city : '',
            cityCode: city ? city.cityCode : '',
            latitude,
            longitude
          }
        }
        this.setData({
          city: city
        })
        this.getHouseByCityInfo(city)
      })
  },

  // 通过经纬度获取小区列表
  getHouseByCityInfo(city) {
    return new Promise((resolve, reject) => {
      if (!city) {
        return reject()
      }
      this.setData({
        loading: true,
      })
      api.listForCooperation({
        lat: city.location.lat,
        lng: city.location.lng,
        pageNo: 1,
        rows: 30,
        city: city.city,
        province: city.province,
        area: city.district,
        isExternal: null
      }, (res) => {
        if (res && res.data && res.data.isSuccess && res.data.content) {
          const {
            rows = []
          } = res.data.content || {}
          this.setData({
            rows: rows || [],
            loading: false,
          })
          resolve()
        } else {
          this.setData({
            loading: false,
          })
          reject()
        }
      }, () => {
        this.setData({
          loading: false,
        })
        reject()
      })
    })
  },

  // 地图区域改变
  onMapRegionChange(e) {
    // 拖动触发
    if (e.causedBy == "drag") {
      this.getCenterLngLat();
    }
  },

  // 获取中心点经纬度
  getCenterLngLat() {
    this.myData.mapCtx.getCenterLocation({
      success: (res) => {
        this.updateMapByCoordinate({
          latitude: res.latitude,
          longitude: res.longitude,
        })
      }
    })
  },

  onSwitchCity() {
    wx.navigateTo({
      url: '/pages/home/switchCity/switchCity',
    })
  },

  onSearchHouse() {
    wx.navigateTo({
      url: '/pages/cooperation/chooseSearch/chooseSearch',
    })
  },

  onAddHouse(e) {
    let villageData = e.currentTarget.dataset.village;
    wx.navigateTo({
      url: `/pages/cooperation/houseEdit/houseEdit?villageData=${JSON.stringify(villageData)}`
    })
  },

  // 检察城市更新
  refreshCity() {
    if (transferData.getData('currentCity')) {
      transferData.resetData('currentCity')
    }
    if (this.myData.entryPageCount > 1) {
      const {
        city,
        _firstCity
      } = this.data
      let currentCity = wx.getStorageSync('currentCity') || {}
      if (city && city.cityCode && currentCity && currentCity.cityCode && city.cityCode != currentCity.cityCode) {
        if (currentCity.cityCode === _firstCity.cityCode) {
          this.resetCityByLocation()
        } else {
          this.resetCityByCityName(currentCity)
        }
      }
    }
  },

  resetCityByCityName(currentCity) {
    if (!currentCity) return;
    this.setData({
      city: {
        city: currentCity.city,
        cityCode: currentCity.cityCode
      },
    })
    qqmapsdk.geocoder({
      address: currentCity.city,
      success: (res) => {
        const {
          location = {}
        } = res.result || {}
        this.setData({
          latitude: location.lat,
          longitude: location.lng,
          markers: [{
            iconPath: "/images/marker.png",
            id: 0,
            latitude: location.lat,
            longitude: location.lng,
            width: 20,
            height: 20,
          }],
        })
        this.updateMapByCoordinate({
          latitude: location.lat,
          longitude: location.lng,
        })
      }
    })
  },

  resetCityByLocation() {
    const {
      _firstCity
    } = this.data
    this.setData({
      city: {
        city: _firstCity.cityName,
        cityCode: _firstCity.cityCode
      },
      latitude: _firstCity.latitude,
      longitude: _firstCity.longitude,
      markers: [{
        iconPath: "/images/marker.png",
        id: 0,
        latitude: _firstCity.latitude,
        longitude: _firstCity.longitude,
        width: 20,
        height: 20,
      }],
    })
    this.updateMapByCoordinate({
      latitude: _firstCity.latitude,
      longitude: _firstCity.longitude,
    })
  }

})